package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.SupplierDao;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.entity.Supplier;
import com.atguigu.jxc.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author nzmxfan
 * @create 2021-09-03-16:41
 */
@Service
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    SupplierDao supplierDao;

    @Override
    public Map<String, Object> list(Integer page, Integer rows, String supplierName) {
        // 定义 list 用来存储后台查询到的 Goods 数据（需要连表查询t_goods、t_goods_type，关联字段：goods_type_id）
        // 参数传到 mapper.xml 中，用来写 sql 语句
        List<Supplier> list = supplierDao.list(((page - 1) * rows), rows, supplierName);
        // 获取总记录数
        int total = supplierDao.total(supplierName);
        // 定义 map，封装返回数据
        Map<String, Object> map = new HashMap<>();
        // 封装为 map
        map.put("total", total);
        map.put("rows", list);
        return map;
    }

    @Override
    public ServiceVO<Supplier> saveOrUpdate(Supplier supplier) {
        Integer supplierId = supplier.getSupplierId();
        ServiceVO<Supplier> vo;
        if (supplierId == null) {
            // 添加
           vo = save(supplier);
        } else {
            // 更新
            vo = update(supplier);
        }
        return vo;
    }

    // 有外键
    @Override
    public ServiceVO<Supplier> deleteById(String[] strings) {
        for (String string : strings) {
            int id = Integer.parseInt(string);
            supplierDao.deleteById(id);
        }
        return new ServiceVO<Supplier>(100, "请求成功", null);
    }

    private ServiceVO<Supplier> update(Supplier supplier) {
        boolean result = supplierDao.update(supplier);
        if (result) {
            // 更新成功
            return new ServiceVO<Supplier>(100, "请求成功", null);
        }
        return new ServiceVO<Supplier>(200,"请求失败",null);
    }

    private ServiceVO<Supplier> save(Supplier supplier) {
        boolean result = supplierDao.save(supplier);
        if (result) {
            // 保存成功
            return new ServiceVO<Supplier>(100, "请求成功", null);
        }
        return new ServiceVO<Supplier>(200,"请求失败",null);
    }
}
